import type { FormInstance } from 'element-plus'
import type { SystemApplicationOptionsType, SystemApplicationDataItemType } from './typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { toPairs } from 'lodash'
import {
  ElDialog,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadioGroup,
  ElRadio,
  ElButton,
  ElMessage,
  ElIcon
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'

export default defineComponent({
  name: 'SystemApplicationOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemApplicationOptionsType, { emit }) {
    const store = useStore()
    const { 'application/appTypeEnum': appTypeEnum, 'application/statusEnum': statusEnum } =
      store.getters
    const ruleFormRef = ref<FormInstance>()
    const title = { add: '新增', update: '编辑', read: '查看' }
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }
    return () => {
      const { type, visible } = props
      const optionsValidateForm = reactive<SystemApplicationDataItemType>(
        Object.assign(
          {
            appName: '',
            appUri: '',
            appAddress: '',
            sort: undefined,
            appType: '',
            status: ''
          },
          props.record
        )
      )
      // 提交表单
      const handleSubmitForm = () => {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validate(async (valid) => {
          if (!valid) return
          const params = { ...optionsValidateForm }
          params.status = Number(params.status) as any
          const res = await store.dispatch(
            type === 'add'
              ? 'application/AddSystemApplicationInfo'
              : 'application/UpdateSystemApplicationInfo',
            params
          )
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })
            handleCloseModal()
          }
        })
      }
      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={optionsValidateForm}>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="appName"
                  label="应用名称"
                  rules={[{ required: true, message: '请输入应用名称' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.appName
                  ) : (
                    <ElInput v-model={optionsValidateForm.appName} placeholder="请输入应用名称" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="appUri"
                  label="应用访问地址"
                  rules={[{ required: true, message: '请输入应用访问地址' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.appUri
                  ) : (
                    <ElInput
                      v-model={optionsValidateForm.appUri}
                      placeholder="请输入应用访问地址"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="appAddress"
                  label="应用部署地址"
                  rules={[{ required: true, message: '请输入应用部署地址' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.appAddress
                  ) : (
                    <ElInput
                      v-model={optionsValidateForm.appAddress}
                      placeholder="请输入应用部署地址"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="sort"
                  label="排序"
                  rules={[{ required: true, message: '请输入排序' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.sort
                  ) : (
                    <ElInputNumber
                      v-model={optionsValidateForm.sort}
                      min={0}
                      controls-position="right"
                      placeholder="请输入排序"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="appType"
                  label="类型"
                  rules={[{ required: true, message: '请输入类型' }]}
                >
                  {type === 'read' ? (
                    appTypeEnum?.[optionsValidateForm.appType] || optionsValidateForm.appType
                  ) : (
                    <ElRadioGroup v-model={optionsValidateForm.appType}>
                      {toPairs(appTypeEnum || {})?.map((item: string[]) => (
                        <ElRadio label={parseInt(item[0])}>{item[1]}</ElRadio>
                      ))}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="status"
                  label="状态"
                  rules={[{ required: true, message: '请输入状态' }]}
                >
                  {type === 'read' ? (
                    statusEnum?.[optionsValidateForm.status] || optionsValidateForm.status
                  ) : (
                    <ElRadioGroup v-model={optionsValidateForm.status}>
                      {toPairs(statusEnum || {})?.map((item: string[]) => (
                        <ElRadio label={parseInt(item[0])}>{item[1]}</ElRadio>
                      ))}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
